/*
 * @(#)MaintDmsQueryRecordAction.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.web;

import java.io.StringWriter;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.xml.sax.InputSource;

import com.dcivision.dms.DmsErrorConstant;
import com.dcivision.dms.bean.DmsQueryRecord;
import com.dcivision.dms.bean.DmsRoot;
import com.dcivision.dms.core.DmsQueryRecordParser;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.dms.core.RootRetrievalManager;
import com.dcivision.dms.dao.DmsQueryRecordDAObject;
import com.dcivision.dms.dao.DmsRootDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.ErrorConstant;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.SysUserDefinedIndex;
import com.dcivision.framework.bean.SysUserDefinedIndexDetail;
import com.dcivision.framework.dao.SysUserDefinedIndexDAObject;
import com.dcivision.framework.web.AbstractListAction;

/**
  MaintDmsQueryRecordAction.java
  This class is for Dms Query Save Function.
    @author          Jenny Li
    @company         DCIVision Limited
    @creation date   30/08/2004
    @version         $Revision: 1.24.2.1 $
 */

public class MaintDmsQueryRecordAction extends AbstractListAction {

  public static final String REVISION = "$Revision: 1.24.2.1 $";


  public MaintDmsQueryRecordAction() {
    super();
     this.setListName("queryRecordList");
  }

  /**
   * getMajorDAOClassName
   *
   * @return  The class name of the major DAObject will be used in this action.
   */
  public String getMajorDAOClassName() {
    return ("com.dcivision.dms.dao.DmsQueryRecordDAObject");
  }

  /**
   * getFunctionCode
   *
   * @return  The corresponding system function code of action.
   */
  public String getFunctionCode() {
    return (null);
  }
  
  /**
   *  Method execute() - generaic function of result list handling               
   *
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @return     ActionForward         Return the action forward object for struts
   *  @throws     ServletException      Throws ServletException
   */
  public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException {
    MaintDmsQueryRecordForm maintForm=(MaintDmsQueryRecordForm)form;
    
    //Set function code if necessary.
    if (!Utility.isEmpty(maintForm.getCurFunctionCode())) {
      this.setFunctionCode(maintForm.getCurFunctionCode());
    }
    
    //Set the function code for current action.
    ActionForward forward = this.retrieveFunctionCode(request, response, mapping);
    if (forward!=null) {
      return forward;
    }

    String opMode=maintForm.getOpMode();
    String navMode=maintForm.getNavMode();
    if(!Utility.isEmpty(opMode)){
      if(GlobalConstant.OP_MODE_INSERT.equals(opMode)){
        //Insert operation.
        String personalError="";  
        try {
          this.insertRecord(mapping, maintForm, request, response);
          this.handleWorkflowRoutine(mapping, maintForm, request, response, opMode, navMode);
          this.commit(request);
          addMessage(request, "common.message.record_inserted");
          personalError=(String)request.getAttribute("personalError");
          if(!Utility.isEmpty(personalError)){
            addError(request,personalError);
          }
        } catch (ApplicationException appEx) {
          this.rollback(request);
          handleApplicationException(request, appEx);
        }
        if (isError(request) && Utility.isEmpty(personalError)) {
          maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
        }else{
          maintForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
        }
      }else if (GlobalConstant.OP_MODE_UPDATE.equals(opMode)) {
        // Update operation.
        String personalError="";
        try {
          this.updateRecord(mapping, maintForm, request, response);
          this.handleWorkflowRoutine(mapping, maintForm, request, response, opMode, navMode);
          this.commit(request);
          addMessage(request, "common.message.record_updated");
          personalError=(String)request.getAttribute("personalError");
          if(!Utility.isEmpty(personalError)){
            addError(request,personalError);
          }
        } catch (ApplicationException appEx) {
          this.rollback(request);
          handleApplicationException(request, appEx);
        }
        if (isError(request) && Utility.isEmpty(personalError)) {
          maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_NEW);
        }else{
          maintForm.setNavMode(GlobalConstant.NAV_MODE_VIEW);
          return mapping.findForward(GlobalConstant.NAV_MODE_VIEW);
        }
      }else if(GlobalConstant.NAV_MODE_LIST.equals(opMode)){
        return super.execute(mapping,form,request,response);
      }else if("NEW.PAGE".equals(opMode)){
        DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(this.getSessionContainer(request),this.getConnection(request));
        if(!Utility.isEmpty(maintForm.getSearchFolder())){
          
          request.setAttribute("searchFolder",maintForm.getSearchFolder());
        }
        if(!Utility.isEmpty(maintForm.getUserDefinedFieldID())){
          List udfDetailList = docRetrievalManager.getUDFDetailList(TextUtility.parseIntegerObj(maintForm.getUserDefinedFieldID()));
          String[] udfDetail_fieldType=new String[udfDetailList.size()];
          String[] udfDetail_fieldOption=new String[udfDetailList.size()];
          String[] udfDetail_value=new String[udfDetailList.size()];
          String[] udfDetail_value_to=new String[udfDetailList.size()];
          String[] udfDetail_exactMatch=new String[udfDetailList.size()];
          for(int i=0;i<udfDetailList.size();i++){
            SysUserDefinedIndexDetail udfDetail=(SysUserDefinedIndexDetail)udfDetailList.get(i);
            /*bug 5240 fix start*/
            //when user defined profile field is empty, old program would insert an unuseful record to the table sys_user_defined_index_detail, and it would make this program execute failure.
            //so add code to avoid it, and all these code can be remove if you use a new database. lee.lv add for bug 5240 in 2006/05/08
            if (udfDetail.getFieldName()==null || udfDetail.getFieldName().equals("")) {
              continue;
            }
            /*bug 5240 fix end */
            udfDetail_fieldType[i]=request.getParameter("udfDetail_FieldType_"+udfDetail.getID().toString());
            udfDetail_fieldOption[i]=request.getParameter("udfDetail_Option_"+udfDetail.getID().toString());
            if("OR".equals(udfDetail_fieldOption[i])){
              udfDetail_fieldOption[i]="true" ;
            }else{
              udfDetail_fieldOption[i]="false";
            }
            if(SysUserDefinedIndexDetail.STRING_FIELD.equals(udfDetail_fieldType[i]) || udfDetail_fieldType[i].startsWith("CUST")){
              udfDetail_value[i]=request.getParameter("udfDetail_String_"+udfDetail.getID().toString());
              udfDetail_value_to[i]=udfDetail_value[i];
              udfDetail_exactMatch[i]=request.getParameter("udfDetail_StringExactMatch_"+udfDetail.getID().toString());
            }else if(SysUserDefinedIndexDetail.DATE_FIELD.equals(udfDetail_fieldType[i])){
              udfDetail_value[i]=request.getParameter("udfDetail_Date_"+udfDetail.getID().toString());
              udfDetail_value_to[i]=request.getParameter("udfDetail_DateTo_"+udfDetail.getID().toString());
              udfDetail_exactMatch[i]="false";
            }else if(SysUserDefinedIndexDetail.NUMBER_FIELD.equals(udfDetail_fieldType[i])){
              udfDetail_value[i]=request.getParameter("udfDetail_Number_"+udfDetail.getID().toString());
              udfDetail_value_to[i]=request.getParameter("udfDetail_NumberTo_"+udfDetail.getID().toString());
              udfDetail_exactMatch[i]="false";
            }else if(SysUserDefinedIndexDetail.FIELD_TYPE_SELECT_DATABASE.equals(udfDetail_fieldType[i])){
              udfDetail_value[i]=request.getParameter("udfDetail_SDB_"+udfDetail.getID().toString());
              udfDetail_value_to[i]=udfDetail_value[i];
              udfDetail_exactMatch[i]="false";
            }
          }
          request.setAttribute("udfDetail_fieldType",udfDetail_fieldType);
          request.setAttribute("udfDetail_fieldOption",udfDetail_fieldOption);
          request.setAttribute("udfDetail_value",udfDetail_value);
          request.setAttribute("udfDetail_value_to",udfDetail_value_to);
          request.setAttribute("udfDetail_exactMatch",udfDetail_exactMatch);
        }
        String queryPriority="";
        if(!Utility.isEmpty(maintForm.getSearchPriority())){
          for(int i=0;i<maintForm.getSearchPriority().length;i++){
            if(i==0){
              queryPriority=maintForm.getSearchPriority()[0];
            }else{
              queryPriority=queryPriority+","+maintForm.getSearchPriority()[i];
            }
          }
        }
        maintForm.setQueryPriority(queryPriority);
        maintForm.setNavMode(GlobalConstant.NAV_MODE_NEW);
        request.setAttribute(GlobalConstant.ACTION_MODE, GlobalConstant.NAV_MODE_NEW);
        return mapping.findForward(GlobalConstant.NAV_MODE_NEW); 
      }
      else{
        return super.execute(mapping,form,request,response);
      }
    }else{
      if(GlobalConstant.NAV_MODE_EDIT.equals(navMode)){ 
        selectRecord(mapping,form,request,response);
        return mapping.findForward(GlobalConstant.NAV_MODE_EDIT); 
      }
      return super.execute(mapping,form,request,response);
    }
  }

  /**
   * this function is to insert data to db.
   * @param mapping
   * @param form
   * @param request
   * @param response
   * @throws ApplicationException
   */
  public void insertRecord(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException{
     try{
      MaintDmsQueryRecordForm maintForm=(MaintDmsQueryRecordForm)form;
      DmsQueryRecordDAObject dmsQueryRecordDAO=new DmsQueryRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
      if(Utility.isEmpty(maintForm.getSearchFolder())){
        throw new ApplicationException(DmsErrorConstant.SELECT_SEARCH_LOCATION); 
      }
      String[] searchFolder=new String[maintForm.getSearchFolder().length];
      if("Y".equals(maintForm.getIsPublic())){
        if(!Utility.isEmpty(maintForm.getSearchFolder())){
          for(int i=0;i<maintForm.getSearchFolder().length;i++){
            if(checkPersonalFloder(maintForm.getSearchFolder()[i],request)){
              if(maintForm.getSearchFolder().length>1){
                request.setAttribute("personalError",DmsErrorConstant.CANNOT_SAVE_PERSONAL_AS_PUBLIC); 
              }else{
                throw new ApplicationException(DmsErrorConstant.CANNOT_SAVE_PERSONAL_AS_PUBLIC);   
              }
            }else{
              searchFolder[i]=maintForm.getSearchFolder()[i];   
            }
          }
        }
      }
      if(!checkDuplicatedQueryName(form,request)){
        DmsQueryRecord dmsQueryRecord=new DmsQueryRecord();
        this.GenQueryXML(dmsQueryRecord,form,request,searchFolder);
        dmsQueryRecord.setUserRecordID(this.getSessionContainer(request).getUserRecordID());
        dmsQueryRecord.setQueryName(maintForm.getQueryName());
        dmsQueryRecord.setDescription(maintForm.getQueryDescription());
        dmsQueryRecord.setIsPublic(maintForm.getIsPublic());
        dmsQueryRecord=(DmsQueryRecord)dmsQueryRecordDAO.insertObject(dmsQueryRecord);
        maintForm.setID(dmsQueryRecord.getID().toString());
      }else{
        throw new ApplicationException(DmsErrorConstant.DUPLICATED_QUERYNAME); 
      }
      
    }catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {}
  }
  
  /**
   *  Method selectRecord() - rewrite parent function.               
   *
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @throws     ServletException      Throws ServletException
   */
  public void selectRecord(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    MaintDmsQueryRecordForm maintForm=(MaintDmsQueryRecordForm)form;
    DmsQueryRecordDAObject dmsQueryRecordDAO=new DmsQueryRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
    DmsQueryRecord dmsQueryRecord=new DmsQueryRecord();
    String ID=maintForm.getID();
    if(!Utility.isEmpty(ID)){
      dmsQueryRecord=(DmsQueryRecord)dmsQueryRecordDAO.getObjectByID(TextUtility.parseIntegerObj(ID));   
      maintForm.setQueryName(dmsQueryRecord.getQueryName());
      maintForm.setQueryDescription(dmsQueryRecord.getDescription());
      maintForm.setIsPublic(dmsQueryRecord.getIsPublic());
    }  
  }
  
  /**
   *  Method updateRecord() - rewrite parent function.               
   *
   *  @param      mapping               ActionMapping from struts
   *  @param      form                  ActionForm from struts
   *  @param      request               HttpServletReuqest
   *  @param      respond               HttpServletRespond
   *  @throws     ServletException      Throws ServletException
   */
  public void updateRecord(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ApplicationException {
    try{
      MaintDmsQueryRecordForm maintForm=(MaintDmsQueryRecordForm)form;
      DmsQueryRecordDAObject dmsQueryRecordDAO=new DmsQueryRecordDAObject(this.getSessionContainer(request),this.getConnection(request));
      DmsQueryRecord dmsQueryRecord=(DmsQueryRecord)dmsQueryRecordDAO.getObjectByID(TextUtility.parseIntegerObj(maintForm.getID()));
      String[] searchFolder=new String [0];
      if(!Utility.isEmpty(maintForm.getSearchFolder())){
         searchFolder=new String[maintForm.getSearchFolder().length];
      }else{
         searchFolder=(String[])request.getAttribute("searchFolder");
      }
      if("N".equals(dmsQueryRecord.getIsPublic()) && "Y".equals(maintForm.getIsPublic())){
        if(!Utility.isEmpty(maintForm.getSearchFolder())){
          for(int i=0;i<maintForm.getSearchFolder().length;i++){
            if(checkPersonalFloder(maintForm.getSearchFolder()[i],request)){
              if(maintForm.getSearchFolder().length>1){
                request.setAttribute("personalError",DmsErrorConstant.CANNOT_SAVE_PERSONAL_AS_PUBLIC); 
              }else{
                throw new ApplicationException(DmsErrorConstant.CANNOT_SAVE_PERSONAL_AS_PUBLIC);   
              }
            }else{
              searchFolder[i]=maintForm.getSearchFolder()[i];   
            }
          }
        }
        this.GenQueryXML(dmsQueryRecord,form,request,searchFolder);
      }
      if(!checkDuplicatedQueryName(form,request)){        
        dmsQueryRecord.setUserRecordID(this.getSessionContainer(request).getUserRecordID());
        dmsQueryRecord.setQueryName(maintForm.getQueryName());
        dmsQueryRecord.setDescription(maintForm.getQueryDescription());
        dmsQueryRecord.setIsPublic(maintForm.getIsPublic());
        dmsQueryRecord=(DmsQueryRecord)dmsQueryRecordDAO.updateObject(dmsQueryRecord);
        maintForm.setID(dmsQueryRecord.getID().toString());
      }else{
        throw new ApplicationException(DmsErrorConstant.DUPLICATED_QUERYNAME); 
      }
      
    }catch (ApplicationException appEx) {
      throw appEx;
    } catch (Exception e) {
      log.error(e, e);
      throw new ApplicationException(ErrorConstant.COMMON_FATAL_ERROR, e);
    } finally {}
  }
    
  /**
   * this function is to general the xml.
   * @param dmsQueryRecord
   * @param form
   * @param request
   */
  public void GenQueryXML(DmsQueryRecord dmsQueryRecord,ActionForm form,HttpServletRequest request,String[] searchFolder) throws ApplicationException{
    //WriterBean writer=new WriterBean();
    try {
      SessionContainer ctx=this.getSessionContainer(request);
      Connection conn=this.getConnection(request);
      RootRetrievalManager rootRetrevalManager = new RootRetrievalManager(ctx, conn);
      SysUserDefinedIndexDAObject sysUserIndexDAO=new SysUserDefinedIndexDAObject(ctx,conn);
      DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(ctx, conn);
      MaintDmsQueryRecordForm queryForm=(MaintDmsQueryRecordForm)form;
      List rootList = rootRetrevalManager.getAllAccessibleRootsList();
      //String[] rootFolder=new String[rootList.size()];
      SysUserDefinedIndex sysUserDefinedIndex=new SysUserDefinedIndex();
      if(!Utility.isEmpty(queryForm.getUserDefinedFieldID())){
         sysUserDefinedIndex=(SysUserDefinedIndex)sysUserIndexDAO.getObjectByID(TextUtility.parseIntegerObj(queryForm.getUserDefinedFieldID()));
      }
      DmsQueryRecordParser queryRecordParser = new DmsQueryRecordParser();
      queryRecordParser.setConnection(conn);
      queryRecordParser.setSessionContainer(ctx);
      queryRecordParser.setRootList(rootList);
      if("Y".equals(queryForm.getIsPublic())){
        queryRecordParser.setSearchFolder(searchFolder); 
      }else{
        queryRecordParser.setSearchFolder(queryForm.getSearchFolder());
      }
  
      queryRecordParser.setDocumentName(queryForm.getDocumentName());
      if("OR".equals(queryForm.getDocumentNameOption())){
        queryRecordParser.setDocumentNameOption("true");
      }else{
        queryRecordParser.setDocumentNameOption("false"); 
      }
      queryRecordParser.setDocumentType(queryForm.getDocumentType());
      if("OR".equals(queryForm.getDocumentTypeOption())){
        queryRecordParser.setDocumentTypeOption("true"); 
      }else{
        queryRecordParser.setDocumentTypeOption("false"); 
      }
      queryRecordParser.setDocumentNameExactMatch(parseString(queryForm.getDocumentNameExactMatch()));
      if("OR".equals(queryForm.getEffectiveDateOption())){
        queryRecordParser.setEffectiveDateOption("true"); 
      }else{
        queryRecordParser.setEffectiveDateOption("false"); 
      }     
      queryRecordParser.setEffectiveStartDate(queryForm.getEffectiveStartDate());
      queryRecordParser.setEffectiveEndDate(queryForm.getEffectiveEndDate());
      queryRecordParser.setCreateDate(queryForm.getCreateDate());
      if("OR".equals(queryForm.getCreateDateOption())){
        queryRecordParser.setCreateDateOption("true");  
      }else{
        queryRecordParser.setCreateDateOption("false"); 
      }    
      queryRecordParser.setCreateToDate(queryForm.getCreateToDate());
      if("OR".equals(queryForm.getUpdateDateOption())){
        queryRecordParser.setUpdateDateOption("true"); 
      }else{
        queryRecordParser.setUpdateDateOption("false"); 
      }
      queryRecordParser.setUpdateDate(queryForm.getUpdateDate());
      queryRecordParser.setUpdateToDate(queryForm.getUpdateToDate());
      if("OR".equals(queryForm.getPriorityOption())){
        queryRecordParser.setPriorityOption("true");
      }else{
        queryRecordParser.setPriorityOption("false");
      }
      queryRecordParser.setQueryPriority(queryForm.getQueryPriority());
      if("OR".equals(queryForm.getReferenceNoOption())){
        queryRecordParser.setReferenceNoOption("true");
      }else{
        queryRecordParser.setReferenceNoOption("false"); 
      }
      queryRecordParser.setReferenceNo(queryForm.getReferenceNo());
      queryRecordParser.setReferenceNoExactMatch(parseString(queryForm.getReferenceNoExactMatch()));
      if("OR".equals(queryForm.getDescriptionOption())){
        queryRecordParser.setDescriptionOption("true"); 
      }else{
        queryRecordParser.setDescriptionOption("false"); 
      }    
      queryRecordParser.setDescription(queryForm.getDescription());
      queryRecordParser.setDescriptionExactMatch(parseString(queryForm.getDescriptionExactMatch()));
      if("OR".equals(queryForm.getCreatorOption())){
        queryRecordParser.setCreatorOption("true");
      }else{
        queryRecordParser.setCreatorOption("false");
      }
      queryRecordParser.setCreator(queryForm.getCreatorID());
      
      String[] userDef=new String[10];
      for(int i=0;i<userDef.length;i++){
        int m=i+1;
        Method getFileMth = queryForm.getClass().getMethod("getUserDef"+m,null); 
        userDef[i]=(String)getFileMth.invoke(queryForm, null);
      }
      queryRecordParser.setUserDef(userDef);
      
      String[] userDefTo=new String[10];
      for(int i=0;i<userDefTo.length;i++){
        int m=i+1;
        Method getFileMth = queryForm.getClass().getMethod("getUserDef"+m+"To",null); 
        userDefTo[i]=(String)getFileMth.invoke(queryForm, null);
      }
      queryRecordParser.setUserDefTo(userDefTo);
      
      String[] userDefDataType=new String[10];
      for(int i=0;i<userDefDataType.length;i++){
        int m=i+1;
        Method getFileMth = queryForm.getClass().getMethod("getUserDef"+m+"DataType",null); 
        userDefDataType[i]=(String)getFileMth.invoke(queryForm, null);
      }
      queryRecordParser.setUserDefDataType(userDefDataType);
      
      String[] userDefOption=new String[10];
      for(int i=0;i<userDefOption.length;i++){
        int m=i+1;
        Method getFileMth = queryForm.getClass().getMethod("getUserDef"+m+"Option",null); 
        if("OR".equals((String)getFileMth.invoke(queryForm, null))){
          userDefOption[i]="true"; 
        }else{
          userDefOption[i]="false"; 
        }
      }
      queryRecordParser.setUserDefOption(userDefOption);
      String[] userDefExactMatch=new String[10];
      userDefExactMatch[0]=parseString(queryForm.getUserDef1ExactMatch());
      userDefExactMatch[1]=parseString(queryForm.getUserDef2ExactMatch());
      userDefExactMatch[2]=parseString(queryForm.getUserDef3ExactMatch());
      userDefExactMatch[3]=parseString(queryForm.getUserDef4ExactMatch());
      userDefExactMatch[4]=parseString(queryForm.getUserDef5ExactMatch());
      userDefExactMatch[5]=parseString(queryForm.getUserDef6ExactMatch());
      userDefExactMatch[6]=parseString(queryForm.getUserDef7ExactMatch());
      userDefExactMatch[7]=parseString(queryForm.getUserDef8ExactMatch());
      userDefExactMatch[8]=parseString(queryForm.getUserDef9ExactMatch());
      userDefExactMatch[9]=parseString(queryForm.getUserDef10ExactMatch());
      queryRecordParser.setUserDefExactMatch(userDefExactMatch);
      queryRecordParser.setUserDefinedFieldID(queryForm.getUserDefinedFieldID());
      if(!Utility.isEmpty(sysUserDefinedIndex)){
        queryRecordParser.setUserDefinedFieldName(sysUserDefinedIndex.getUserDefinedType());
      }
      queryRecordParser.setUserDefinedFieldOption(queryForm.getUserDefinedFieldOption());
      queryRecordParser.setUdfDetail_fieldType(queryForm.getUdfDetail_fieldType());
      queryRecordParser.setUdfDetail_fieldOption(queryForm.getUdfDetail_fieldOption());
      queryRecordParser.setUdfDetail_value(queryForm.getUdfDetail_value());
      queryRecordParser.setudfDetail_value_to(queryForm.getUdfDetail_value_to());
      queryRecordParser.setUdfDetail_exactMatch(queryForm.getUdfDetail_exactMatch());


      // Use a Transformer for output
      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer();
      // Use the parser as a SAX source for input
      InputSource inputSource = new InputSource(); // no need to take input xml file
      SAXSource source = new SAXSource(queryRecordParser, inputSource);
      StringWriter writer=new StringWriter();
      StreamResult result = new StreamResult(writer);
      transformer.transform(source, result);
      //JobDataMap dataMap = new JobDataMap();
      //dataMap.put("XML_QUERY",writer);
      StringBuffer writerBuffer=new StringBuffer();
      writerBuffer.append(writer.toString());
      dmsQueryRecord.setXmlQuery(writerBuffer);
    } catch (Exception e) {
      log.error(e, e);
    }
  }

  /**
   * parse the Boolean to String.
   * @param exactMatch
   * @return
   */
  protected String parseString(boolean exactMatch){
    String exMatch=""+exactMatch+"";
    return exMatch;
  }
  
  /**
   * this function is to check has duplicated query name.
   * @param form
   * @param request
   * @return
   * @throws ApplicationException
   */
  protected boolean checkDuplicatedQueryName(ActionForm form,HttpServletRequest request) throws ApplicationException{
    MaintDmsQueryRecordForm maintForm=(MaintDmsQueryRecordForm)form;
    SessionContainer sessionContainer=this.getSessionContainer(request);
    Connection conn=this.getConnection(request);
    DmsQueryRecordDAObject dmsQueryRecordDAO=new DmsQueryRecordDAObject(sessionContainer,conn);
    /*
    if("Y".equals(maintForm.getIsPublic())){
      DmsQueryRecord dmsQueryRecord = (DmsQueryRecord)dmsQueryRecordDAO.getListByQueryName(maintForm.getQueryName(),maintForm.getIsPublic());
      if(dmsQueryRecord!=null){
        if(!Utility.isEmpty(maintForm.getID())){
          if(!maintForm.getID().equals(dmsQueryRecord.getID().toString())){
            return true;
          }
        }else{
          return true;
        }
      }
    }else{
      DmsQueryRecord dmsQueryRecord = (DmsQueryRecord)dmsQueryRecordDAO.getListByQueryName(maintForm.getQueryName(),maintForm.getIsPublic(),sessionContainer.getUserRecordID());
      if(dmsQueryRecord!=null){
        if(!Utility.isEmpty(maintForm.getID())){
          if(!maintForm.getID().equals(dmsQueryRecord.getID().toString())){
            return true;
          }
        }else{
          return true;
        }
      }
    }
    return false;
    */
    //Update By Jim Zhou        2007/01/25      EIP-1505
    DmsQueryRecord dmsQueryRecordPublic = (DmsQueryRecord)dmsQueryRecordDAO.getListByQueryName(maintForm.getQueryName(),GlobalConstant.TRUE);
    if (!Utility.isEmpty(dmsQueryRecordPublic)){
      if (!Utility.isEmpty(maintForm.getID())) {
        if (!maintForm.getID().equals(dmsQueryRecordPublic.getID().toString())){
          return true;
        }
      } else {
        return true;
      }
    }
    DmsQueryRecord dmsQueryRecordPersonal = (DmsQueryRecord)dmsQueryRecordDAO.getListByQueryName(maintForm.getQueryName(),GlobalConstant.FALSE,sessionContainer.getUserRecordID());
    if(!Utility.isEmpty(dmsQueryRecordPersonal)){
      if(!Utility.isEmpty(maintForm.getID())){
        if(!maintForm.getID().equals(dmsQueryRecordPersonal.getID().toString())){
          return true;
        }
      }else{
        return true;
      }
    }
    return false;
  }
  
  /**
   * check is personal folder or public.
   * @param searchFolder
   * @param request
   * @return
   * @throws ApplicationException
   */
  protected boolean checkPersonalFloder(String searchFolder,HttpServletRequest request) throws ApplicationException {
    DmsRootDAObject dmsRootDAO=new DmsRootDAObject(this.getSessionContainer(request),this.getConnection(request));
    //for(int i=0;i<searchFolder.length;i++){
      DmsRoot dmsRoot=(DmsRoot)dmsRootDAO.getObjectByID(TextUtility.parseIntegerObj(searchFolder));    
      if(DmsRoot.PERSONAL_ROOT.equals(dmsRoot.getRootType())){
        return true; 
      }
   // }
    return false;
  }

}
